package com.example.myapplication

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication.utils.ServerConfig
import kotlinx.coroutines.*
import android.util.Log

class ServerSettingsActivity : AppCompatActivity() {
    
    private lateinit var radioButtonLocal: RadioButton
    private lateinit var radioButtonPublic: RadioButton
    private lateinit var radioButtonAuto: RadioButton
    private lateinit var editTextServerUrl: EditText
    private lateinit var textViewCurrentServer: TextView
    private lateinit var textViewAvailableServers: TextView
    private lateinit var buttonSave: Button
    private lateinit var buttonTest: Button
    private lateinit var buttonAddBackup: Button
    private lateinit var switchAutoSwitch: Switch
    private lateinit var buttonRefreshServers: Button
    
    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_server_settings)
        
        initViews()
        loadCurrentSettings()
        setupListeners()
        refreshAvailableServers()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        scope.cancel()
    }
    
    private fun initViews() {
        radioButtonLocal = findViewById(R.id.radioButtonLocal)
        radioButtonPublic = findViewById(R.id.radioButtonPublic)
        radioButtonAuto = findViewById(R.id.radioButtonAuto)
        editTextServerUrl = findViewById(R.id.editTextServerUrl)
        textViewCurrentServer = findViewById(R.id.textViewCurrentServer)
        textViewAvailableServers = findViewById(R.id.textViewAvailableServers)
        buttonSave = findViewById(R.id.buttonSave)
        buttonTest = findViewById(R.id.buttonTest)
        buttonAddBackup = findViewById(R.id.buttonAddBackup)
        switchAutoSwitch = findViewById(R.id.switchAutoSwitch)
        buttonRefreshServers = findViewById(R.id.buttonRefreshServers)
    }
    
    private fun loadCurrentSettings() {
        val isUsingPublicServer = ServerConfig.isUsingPublicServer(this)
        val serverInfo = ServerConfig.getServerInfo(this)
        
        if (isUsingPublicServer) {
            radioButtonPublic.isChecked = true
            editTextServerUrl.setText(ServerConfig.getServerUrl(this))
        } else {
            radioButtonLocal.isChecked = true
        }
        
        textViewCurrentServer.text = "当前服务器: $serverInfo"
        
        // 加载自动切换设置
        val prefs = getSharedPreferences("server_config", MODE_PRIVATE)
        switchAutoSwitch.isChecked = prefs.getBoolean("auto_switch", true)
    }
    
    private fun setupListeners() {
        radioButtonLocal.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                editTextServerUrl.isEnabled = false
                editTextServerUrl.setText("")
            }
        }
        
        radioButtonPublic.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                editTextServerUrl.isEnabled = true
                editTextServerUrl.setText("ws://8.140.59.178:8080")
            }
        }
        
        radioButtonAuto.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                editTextServerUrl.isEnabled = false
                editTextServerUrl.setText("智能选择最佳服务器")
            }
        }
        
        buttonSave.setOnClickListener {
            saveSettings()
        }
        
        buttonTest.setOnClickListener {
            testConnection()
        }
        
        buttonAddBackup.setOnClickListener {
            showAddBackupServerDialog()
        }
        
        switchAutoSwitch.setOnCheckedChangeListener { _, isChecked ->
            ServerConfig.setAutoSwitchEnabled(this, isChecked)
            Toast.makeText(this, "自动切换: ${if (isChecked) "开启" else "关闭"}", Toast.LENGTH_SHORT).show()
        }
        
        buttonRefreshServers.setOnClickListener {
            refreshAvailableServers()
        }
    }
    
    private fun saveSettings() {
        try {
            if (radioButtonLocal.isChecked) {
                ServerConfig.switchToLocalServer(this)
                Toast.makeText(this, "已切换到本地服务器", Toast.LENGTH_SHORT).show()
            } else if (radioButtonPublic.isChecked) {
                val url = editTextServerUrl.text.toString().trim()
                if (url.isEmpty()) {
                    Toast.makeText(this, "请输入服务器地址", Toast.LENGTH_SHORT).show()
                    return
                }
                if (!ServerConfig.isValidServerUrl(url)) {
                    Toast.makeText(this, "服务器地址格式错误，应以ws://或wss://开头", Toast.LENGTH_SHORT).show()
                    return
                }
                ServerConfig.setPublicServerUrl(this, url)
                Toast.makeText(this, "已设置公网服务器", Toast.LENGTH_SHORT).show()
            } else if (radioButtonAuto.isChecked) {
                // 启用智能选择模式
                ServerConfig.setAutoSwitchEnabled(this, true)
                ServerConfig.switchToLocalServer(this) // 默认使用本地模式，但允许自动切换
                Toast.makeText(this, "已启用智能服务器选择", Toast.LENGTH_SHORT).show()
            }
            
            loadCurrentSettings()
            refreshAvailableServers()
        } catch (e: Exception) {
            Toast.makeText(this, "保存设置失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun testConnection() {
        scope.launch {
            try {
                val serverUrl = if (radioButtonAuto.isChecked) {
                    ServerConfig.getBestServerUrl(this@ServerSettingsActivity)
                } else {
                    ServerConfig.getServerUrl(this@ServerSettingsActivity)
                }
                
                Toast.makeText(this@ServerSettingsActivity, "正在测试连接: $serverUrl", Toast.LENGTH_SHORT).show()
                
                // 这里可以添加实际的连接测试逻辑
                // 使用WebSocket管理器进行测试连接
                val webSocketManager = com.example.myapplication.realtime.WebSocketManager.getInstance(this@ServerSettingsActivity)
                webSocketManager.connect()
                
                Toast.makeText(this@ServerSettingsActivity, "连接测试已启动，请查看连接状态", Toast.LENGTH_LONG).show()
            } catch (e: Exception) {
                Toast.makeText(this@ServerSettingsActivity, "测试连接失败: ${e.message}", Toast.LENGTH_LONG).show()
                Log.e("ServerSettings", "测试连接失败", e)
            }
        }
    }
    
    private fun showAddBackupServerDialog() {
        val editText = EditText(this)
        editText.hint = "输入备用服务器地址（如：ws://192.168.1.100:8080）"
        
        AlertDialog.Builder(this)
            .setTitle("添加备用服务器")
            .setView(editText)
            .setPositiveButton("添加") { _, _ ->
                val url = editText.text.toString().trim()
                if (url.isNotEmpty() && ServerConfig.isValidServerUrl(url)) {
                    ServerConfig.addBackupServer(this, url)
                    Toast.makeText(this, "备用服务器已添加", Toast.LENGTH_SHORT).show()
                    refreshAvailableServers()
                } else {
                    Toast.makeText(this, "请输入有效的服务器地址", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun refreshAvailableServers() {
        scope.launch {
            try {
                val servers = ServerConfig.getAllAvailableServers(this@ServerSettingsActivity)
                val serversText = "可用服务器列表：\n" + servers.joinToString("\n") { "• $it" }
                textViewAvailableServers.text = serversText
            } catch (e: Exception) {
                Log.e("ServerSettings", "刷新服务器列表失败", e)
                textViewAvailableServers.text = "无法获取服务器列表"
            }
        }
    }
} 